// src/pages/ForexTrend/ForexTrend.jsx
import React, { useLayoutEffect, useEffect, useRef, useState } from 'react';
import * as echarts from 'echarts';
import { Card, Spin, message, Input } from 'antd';
import { useSearchParams } from 'react-router-dom';
import { $fetchForexTrend } from '../../api/forexApi';
import './ForexTrend.scss';

const { Search } = Input;

const ForexTrend = () => {
  // 1. 从 URL query string 读取 symbol
  const [searchParams] = useSearchParams();
  const propSymbol = searchParams.get('symbol') || '';
  // 2. 内部 symbol 状态，初始化时取 URL 中的值
  const [symbol, setSymbol] = useState(propSymbol);
  // 3. 控制 loading 转圈
  const [loading, setLoading] = useState(false);

  // 4. ECharts 相关引用
  const chartRef = useRef(null);
  const chartInstance = useRef(null);

  // 5. 当 URL 参数变化时，同步更新内部 symbol
  useEffect(() => {
    if (propSymbol && propSymbol !== symbol) {
      setSymbol(propSymbol);
    }
  }, [propSymbol]);

  // 6. 初始化 ECharts（只执行一次）
  useLayoutEffect(() => {
    if (!chartRef.current) return;
    const container = chartRef.current;
    chartInstance.current = echarts.init(container);

    // 初始时给空白配置，提示“请输入代码并加载”
    chartInstance.current.setOption({
      title: {
        text: '请输入外汇代码并点击“加载”',
        left: 'center',
        textStyle: { fontSize: 14, color: '#888' },
      },
      tooltip: { trigger: 'none' },
      xAxis: { type: 'category', data: [], axisLabel: { rotate: 45 } },
      yAxis: [{ type: 'value', name: '最新价' }],
      series: [],
    });

    // 延迟一次 resize
    setTimeout(() => {
      chartInstance.current?.resize();
    }, 0);

    // 监听窗口 resize
    const handleResize = () => chartInstance.current?.resize();
    window.addEventListener('resize', handleResize);

    return () => {
      window.removeEventListener('resize', handleResize);
      chartInstance.current?.dispose();
      chartInstance.current = null;
    };
  }, []);

  // 7. 当 symbol 变化时，拉取数据并绘图
  useEffect(() => {
    if (!symbol) return;
    const chart = chartInstance.current;
    if (!chart) return;

    const fetchData = async () => {
      setLoading(true);
      chart.resize();
      chart.showLoading({
        text: '数据加载中...',
        color: '#3399FF',
        textColor: '#333',
      });

      try {
        // 7.1 调用 API → 获取 Array<Object>
        const rawData = await $fetchForexTrend(symbol);
        console.log('[ForexTrend] 接口返回 rawData =', rawData);

        if (!Array.isArray(rawData) || rawData.length === 0) {
          throw new Error('后端返回数据为空或格式不对');
        }

        // 7.2 解析字段：date、close、amplitude
        const parsed = rawData.map(item => {
          // 取 item['date']，假设格式为 "YYYY-MM-DD" 或带 GMT 字符串
          const dateStr = item['date'];
          // 时间戳用于排序
          const ts = new Date(dateStr).getTime();
          return {
            ts,
            dateLabel:
              dateStr.length === 10
                ? dateStr
                : new Date(dateStr).toISOString().slice(0, 10),
            latest: parseFloat(item['close']),       // 最新价
            amplitude: parseFloat(item['amplitude']), // 振幅
          };
        });

        // 7.3 按时间升序排序
        parsed.sort((a, b) => a.ts - b.ts);

        // 7.4 拆分成 dates、latestPrices、amplitudes 三个数组
        const dates = parsed.map(p => p.dateLabel);
        const latestPrices = parsed.map(p => p.latest);
        const amplitudes = parsed.map(p => p.amplitude);

        chart.hideLoading();

        // 7.5 构造 ECharts Option
        const finalOption = {
          title: {
            text: `${symbol} 外汇历史走势`,
            left: 'center',
            textStyle: { fontSize: 16 },
          },
          tooltip: {
            trigger: 'axis',
            axisPointer: { type: 'cross' },
            formatter: params => {
              // params 中会包含两个系列：最新价 和 振幅
              const lp = params.find(s => s.seriesName === '最新价');
              const ap = params.find(s => s.seriesName === '振幅');
              const date = lp ? lp.axisValueLabel : '';
              const latestVal = lp ? lp.data : '-';
              const amplitudeVal = ap ? ap.data : '-';
              return (
                date +
                '<br/>' +
                '最新价：' +
                latestVal +
                '<br/>' +
                '振幅：' +
                amplitudeVal +
                '%'
              );
            },
          },
          legend: {
            top: 30,
            data: ['最新价', '振幅'],
          },
          xAxis: {
            type: 'category',
            data: dates,
            boundaryGap: false,
            axisLabel: { rotate: 45, fontSize: 12 },
          },
          yAxis: [
            {
              name: '最新价',
              type: 'value',
              position: 'left',
              axisLabel: { formatter: '{value}' },
            },
            {
              name: '振幅(%)',
              type: 'value',
              position: 'right',
              offset: 60,
              axisLabel: { formatter: '{value} %' },
            },
          ],
          dataZoom: [
            { type: 'inside', xAxisIndex: 0 },
            { type: 'slider', xAxisIndex: 0 },
          ],
          series: [
            {
              name: '最新价',
              type: 'line',
              data: latestPrices,
              yAxisIndex: 0,
              smooth: true,
              showSymbol: false,
            },
            {
              name: '振幅',
              type: 'bar',
              data: amplitudes,
              yAxisIndex: 1,
              barWidth: '60%',
            },
          ],
        };

        console.log('[ForexTrend] finalOption =', finalOption);
        chart.setOption(finalOption);

        // 7.6 再次强制 resize
        setTimeout(() => {
          chart.resize();
        }, 0);
      } catch (err) {
        console.error('[ForexTrend] 拉取或绘制失败：', err);
        message.error(err.message || '获取外汇数据失败');
        chart.hideLoading();
      } finally {
        setLoading(false);
      }
    };

    fetchData();
  }, [symbol]);

  return (
    <Card
      className="forex-trend-chart"
      title="外汇历史可视化"
      // 即使从列表页跳转过来，无需再次搜索，URL 中已有 symbol
      extra={
        <Search
          placeholder="输入外汇对代码（如: USDCNH）"
          allowClear
          enterButton="加载"
          onSearch={value => {
            const v = value.trim();
            if (!v) {
              message.warning('请输入有效的外汇对代码');
              return;
            }
            setSymbol(v);
          }}
          style={{ width: 300 }}
        />
      }
    >
      <Spin spinning={loading} tip="加载中..." className="spin-center">
        <div ref={chartRef} className="chart-container" />
      </Spin>
    </Card>
  );
};

export default ForexTrend;
